import { getPasswordRules, getSmsCodeRules } from '@/utils/page/rules';
import type { FormItemRule, FormRules } from 'element-plus';
import { type EditPasswordRequest, SmsType, editPasswordAxios, sendAuthCodeByUserAxios } from '@/api/login';

export type EditPasswordForm = EditPasswordRequest & { affirmPassword: string };

/** 修改密码 */
export function useEditPassword() {
  const { smsCodeLen, smsCodeRules } = getSmsCodeRules();
  const { passwordMax, passwordRules } = getPasswordRules();
  const editPasswordPnputCountDownRef: $RefComp<'BaseInputCountDown'> = ref(null);
  const editPasswordFormRef: $RefComp<'ElForm'> = ref(null);
  const passdLoading = ref(false);

  const editPasswordForm: EditPasswordForm = reactive({
    smsCode: '',
    password: '',
    affirmPassword: '',
  });

  const editPasswordRules = computed<FormRules<EditPasswordForm>>(() => {
    const _rules: FormRules<EditPasswordForm> = {
      smsCode: smsCodeRules,
      password: passwordRules('新密码'),
      affirmPassword: passwordRules('确认密码'),
    };
    if (editPasswordForm.password) {
      const regExp = RegExp(`^${editPasswordForm.password}$`);
      const affirmRules: FormItemRule = { pattern: regExp, type: 'string', message: '两次输入密码不一致', trigger: ['blur', 'change'] };
      (_rules.affirmPassword as FormItemRule[]).push(affirmRules);
    }
    return _rules;
  });

  /** 修改密码 */
  async function submitEditPassword() {
    try {
      await editPasswordFormRef.value?.validate();
      try {
        passdLoading.value = true;
        await editPasswordAxios({ password: editPasswordForm.password, smsCode: editPasswordForm.smsCode });
        passdLoading.value = false;
        useUserStore().logout(false);
        ElToast.success('修改成功');
      } catch (error) {
        passdLoading.value = false;
        ElToast.error(error.msg || '提交失败，-BD003');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD001');
    }
  }
  return {
    passdLoading,
    editPasswordFormRef,
    editPasswordRules,
    passwordMax,
    editPasswordForm,
    smsCodeLen,
    /** 输入验证码组件实例 */
    editPasswordPnputCountDownRef,
    /** 发送验证码 */
    sendAuthCodeByUserAxios: () => sendAuthCodeByUserAxios(SmsType.AppSMSUpdatePassword),
    /** 提交修改密码 */
    submitEditPassword,
  };
}
